package httpx

import (
	"fmt"
	"io"
	"net/http"
)

type ReadFunc = func(r io.Reader) error

//Process 处理下载流
func Process(process ProcessFunc) ProcessFunc {
	return func(resp *http.Response) (err error) {
		defer func() {
			if re := recover(); re != nil {
				if ex, ok := re.(error); ok {
					err = ex
				} else {
					err = fmt.Errorf("%v", re)
				}
			}
		}()
		defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body)
		err = process(resp)
		return
	}
}

//Read 处理下载流
func Read(readFn ReadFunc) ProcessFunc {
	return Process(func(resp *http.Response) (err error) {
		err = readFn(resp.Body)
		return
	})
}

//ProcessBytes 以字节方式处理下载流
func ProcessBytes(process func(data []byte) error) ProcessFunc {
	return Read(func(r io.Reader) error {
		if data, err := io.ReadAll(r); err == nil {
			return process(data)
		} else {
			return err
		}
	})
}
